<template>
  <div style="width: 50%; margin: 0 auto" class="card">
    <el-form ref="fromRef" :rules="data.rules" :model="data.user" label-width="100px" style="padding: 20px">
      <el-form-item prop="avatar" label="头像">
        <el-upload
          :action="baseUrl + '/files/upload'"
          :on-success="handleFileUpload"
          :show-file-list="false"
          class="avatar-uploader"
        >
          <img v-if="data.user.avatar" :src="data.user.avatar" class="avatar" />
          <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
        </el-upload>
      </el-form-item>
      <el-form-item prop="username" label="用户名">
        <el-input disabled v-model="data.user.username" placeholder="请输入用户名"></el-input>
      </el-form-item>
      <el-form-item prop="name" label="宠物店名称" v-if="data.user.role === 'PETSHOP'">
        <el-input v-model="data.user.name" placeholder="请输入宠物店名称"></el-input>
      </el-form-item>
      <el-form-item prop="name" label="昵称" v-if="data.user.role === 'ADMIN'">
        <el-input v-model="data.user.name" placeholder="请输入昵称"></el-input>
      </el-form-item>
      <el-form-item prop="sellPet" label="销售宠物类型" v-if="data.user.role === 'PETSHOP'">
        <el-select multiple style="width: 100%" v-model="data.sellPet">
          <el-option v-for="item in data.petTypeList" :key="item.id" :value="item.name" :label="item.name"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item prop="address" label="宠物店地址" v-if="data.user.role === 'PETSHOP'">
        <el-input type="textarea" :rows="3" v-model="data.user.address" placeholder="请输入宠物店地址"></el-input>
      </el-form-item>
      <el-form-item prop="introduce" label="宠物店介绍" v-if="data.user.role === 'PETSHOP'">
        <el-input type="textarea" :rows="3" v-model="data.user.introduce" placeholder="请输入宠物店介绍"></el-input>
      </el-form-item>
      <el-form-item prop="phone" label="电话">
        <el-input v-model="data.user.phone" placeholder="请输入电话"></el-input>
      </el-form-item>
      <el-form-item prop="email" label="邮箱">
        <el-input v-model="data.user.email" placeholder="请输入邮箱"></el-input>
      </el-form-item>
      <div style="text-align: center">
        <el-button type="primary" @click="handleUpdate">保 存</el-button>
      </div>
    </el-form>
  </div>
</template>

<script setup>
  import {reactive, ref} from 'vue'
  import request from '@/utils/request.js'
  import { ElMessage } from 'element-plus'

  const baseUrl = import.meta.env.VITE_BASE_URL

  const fromRef = ref()

  const validatePhone = (rule, value, callback) => {
    if (value && !/^1[3-9]\d{9}$/.test(value)) {
      callback(new Error('手机号格式不正确'));
    } else {
      callback();
    }
  };

  const validateEmail = (rule, value, callback) => {
    if (value && !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(value)) {
      callback(new Error('邮箱格式不正确'));
    } else {
      callback();
    }
  };

  const data = reactive({
    user: JSON.parse(localStorage.getItem('xm-user') || '{}'),
    sellPet: [],
    petTypeList: [],
    rules : {
      phone: [{ validator: validatePhone, trigger: 'blur' }],
      email: [{ validator: validateEmail, trigger: 'blur' }]
    }
  })

  request.get('/petType/query/all').then(res => {
    if (res.code === '200') {
      data.petTypeList = res.data
    } else {
      ElMessage.error(res.msg)
    }
  })

  if (data.user.role === 'PETSHOP') {
    data.sellPet = JSON.parse(data.user.sellPet || '[]')
  }

  const handleFileUpload = (res) => {
    data.user.avatar = res.data
  }

  const emit = defineEmits(['updateUser'])

  const handleUpdate = () => {
    fromRef.value.validate(validate => {
      if (validate) {
        if (data.user.role === 'ADMIN') {
          request.put('/admin/update', data.user).then(res => {
            if (res.code === '200') {
              ElMessage.success('成功更新个人资料')
              localStorage.setItem('xm-user', JSON.stringify(data.user))
              emit('updateUser')
            } else {
              ElMessage.error(res.msg)
            }
          })
        } else if (data.user.role === 'PETSHOP') {
          data.user.sellPet = JSON.stringify(data.sellPet)
          request.put('/petShop/update', data.user).then(res => {
            if (res.code === '200') {
              ElMessage.success('成功更新个人资料')
              localStorage.setItem('xm-user', JSON.stringify(data.user))
              emit('updateUser')
            } else {
              ElMessage.error(res.msg)
            }
          })
        }
      }
    })
  }

</script>

<style scoped>
.avatar-uploader {
  height: 120px;
}

.avatar-uploader .avatar {
  width: 120px;
  height: 120px;
  display: block;
}

.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 120px;
  height: 120px;
  text-align: center;
}
</style>